package com.infinitegroup.findmystuff.presenters;

import java.util.List;
import java.util.Map;

import android.content.Context;
import com.infinitegroup.findmystuff.models.Item;
import com.infinitegroup.findmystuff.models.ItemLink;
import com.infinitegroup.findmystuff.views.ViewAllView;

/**
 * Controls the view all/search activity for the app.
 * @author Stephen
 *
 */
public class ViewAllPresenter{
	
	private Item item;
	private ViewAllView view;
	
	/**
	 * ViewAllPresenter constructor
	 * @param view The view associated with the activoty that the presenter controls.
	 */
	public ViewAllPresenter(ViewAllView view){
		this.view = view;
		this.item = new ItemLink((Context) view);
	}
	
	/**
	 * Gets items in the database and returns them as a list of maps.
	 * @return List of items (maps).
	 */
	public List<Map<String,String>> getItemsToDisplay(String itemname, String location, String category, String status, String orderBy) {
		try{
			if (itemname.equals("")) itemname = null;
			if (location.equals("")) location = null;
			if (category.equals("")) category = null;
			if (status.equals("")) status = null;
			if (orderBy.equals("")) orderBy = null;
			List<Map<String,String>> items = item.getItemsFilteredBy(itemname, location, status, category, orderBy);
			if (items.isEmpty()){
				view.displayMessage("No items found.");
				return null;
			} 
			else {
				return items;
			}
		} 
		catch (Exception e){
			view.displayMessage("Could not fetch items from database");
			e.printStackTrace();
			return null;
		}
	}
	/**
	 * Handles a click of the filter button by sorting through the database for items that match
	 * the inputed parameters. 
	 * 
	 * @param itemname User imputed name of the item
	 * @param category User inputed category of the item
	 * @param status User inputed status of the item
	 * @param location User inputed location of the item
	 * @param orderBy User inputed preference of order by
	 */
	public void handleFilterClick(String itemname, String category, String status, String location, String orderBy){
		try{
			if (itemname.equals("")) itemname = null;
			if (location.equals("")) location = null;
			if (category.equals("")) category = null;
			if (status.equals("")) status = null;
			if (orderBy.equals("")) orderBy = null;
			List<Map<String,String>> items = item.getItemsFilteredBy(itemname, location, status, category, orderBy);
			if (items.isEmpty()){
				view.displayMessage("No items found.");
			} 
			else {
				view.generateViewAllScreen(items);
			}
		} 
		catch (Exception e){
			view.displayMessage("Could not fetch items from database");
		}
	}
	
	public void handleReturnToHomeClick(){
		view.end();
	}
}
